<?php
/**
 * Amazon广告账号（基础）
 * (model)
 */

namespace App\Models\Basics;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class AmazonAccountAds extends Model
{
    protected $connection = 'mysql';

    protected $table = 'b_amazon_account_ads';

    protected $guarded = [];

    const AUTH_AT_EXPIRED = 7 * 3600 * 24;

    public static $_authStatus = [
        0 => '未授权',
        1 => '已授权',
    ];

    public static $_api = [
        0 => '停用',
        1 => '启用',
    ];

    /**
     * 广告授权网站（地区）
     * @var string[]
     */
    public static $_authUrl = [
        'NA' => 'https://www.amazon.com/ap/oa', //北美洲 (NA)
        'EU' => 'https://eu.account.amazon.com/ap/oa', //欧洲 (EU)
        'FE' => 'https://apac.account.amazon.com/ap/oa' //远东 (FE)
    ];

    public function amazon_account(){
        return $this->belongsTo(AmazonAccount::class,'account_id');
    }

    public static function options($where = [])
    {
        $query = $where ? self::query()->where(formatCondition($where)) : self::query();
        $data = $query->get()->map(function ($model){
            return collect([
                'id' => $model->account_id,
                'account' => $model->amazon_account->account,
            ]);
        });
        return $data->pluck('account','id');
    }

    public static function getAccountById($accountId){
        return AmazonAccount::query()->where('id',$accountId)->value('account');
    }

    public static function getModel($accountId)
    {
        return self::query()->where('account_id',$accountId)->first();
    }

    public static function optionsForApi($where = [])
    {
        $query = $where ? self::query()->where(formatCondition($where)) : self::query();
        return $query->where('auth_status',1)->orderBy('id')->get();
    }

    /**
     * 获取账号授权信息【集合】
     * @param int $accountId
     * @return Builder[]|Collection
     */
    public static function _getAccounts(int $accountId = 0): Collection|array
    {
        $where = $accountId ? ['account_id' => $accountId] : ['api' => 1];
        return self::optionsForApi($where);
    }

    /**
     * 获取账号授权信息【单个】
     * @param int $accountId
     * @return Model|Builder|null
     */
    public static function _getAccount(int $accountId): Model|Builder|null
    {
        return self::getModel($accountId);
    }

}
